package com.animee.tally;
import androidx.appcompat.app.AppCompatActivity;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.animee.tally.adapter.AccountAdapter;
import com.animee.tally.db.AccountBean;
import com.animee.tally.db.DBManager;
import com.animee.tally.util.BudgetDialog;
import com.animee.tally.util.FloatUtil;
import com.animee.tally.util.MoreDialog;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    Button editBtn;   //记一笔按钮
    ImageButton moreIB;  // 更多按钮
    ImageView searchIv;   //搜索按钮
    ListView todayLv;   //展示今日的收入和支出情况
    // 显示数据源
    List<AccountBean>mDatas;
    AccountAdapter adapter;
   //  顶部控件
    TextView topOutTv,topInTv,topbudgetTv,topConTv;
    ImageView topShowIv;
    View headerView;
    // 记录今天年,月,日
    int year,month,day;

    SharedPreferences preferences;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initTime();
        preferences = getSharedPreferences("budget", Context.MODE_PRIVATE);
        initView();
        mDatas = new ArrayList<>();
        //设置适配器  加载每一行数据到列表当中
        adapter = new AccountAdapter(this, mDatas);
        todayLv.setAdapter(adapter);
        //设置ListView的长按事件
        setLVLongClickListener();
    }
    /* 设置ListView长按事件*/
    private void setLVLongClickListener() {
        todayLv.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                if (position==0){//点击了头部
                    return false;
                }
                int pos = position - 1;
                final AccountBean bean = mDatas.get(pos);
                final int ac_id = bean.getId();
                //弹出对话框，提示用户是否确定要删除
                AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
                builder.setTitle("提示信息").setMessage("您确定要删除这条记录么?")
                        .setNegativeButton("取消",null)
                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                 DBManager.deleteItemFromAccountById(ac_id);
                                 mDatas.remove(bean);    //从集合当中移除对象
                                 adapter.notifyDataSetChanged();
                                 setTopTvShow();
                            }
                        });
                 builder.create().show();
                return false;
            }});
    }

    // 当activity获取到焦点时，加载数据
    @Override
    protected void onResume() {
        super.onResume();
        loadDBData();
        setTopTvShow();
    }
    /* 加载数据库当中今日收入和支出情况*/
    private void loadDBData() {
        List<AccountBean> listOneDay = DBManager.getAccountListOneDay(year, month, day);
        //将得到的数据，添加到ListView的数据源当中
        mDatas.clear();
        mDatas.addAll(listOneDay);
        adapter.notifyDataSetChanged();
    }
   /* 获取今日时间信息的方法*/
    private void initTime() {
        Calendar calendar = Calendar.getInstance();
        year = calendar.get(Calendar.YEAR);
        month = calendar.get(Calendar.MONTH)+1;
        day = calendar.get(Calendar.DAY_OF_MONTH);
    }
    // 初始化View的操作
    private void initView() {
        editBtn = findViewById(R.id.main_btn_edit);
        moreIB = findViewById(R.id.main_btn_more);
        searchIv = findViewById(R.id.main_iv_search);
        todayLv = findViewById(R.id.main_lv);
        editBtn.setOnClickListener(this);   //设置按钮的监听事件
        moreIB.setOnClickListener(this);
        searchIv.setOnClickListener(this);
        addLVHeaderView();
    }
    /* 给ListView添加头布局的方法*/
    private void addLVHeaderView() {
        //1.将布局转换成View对象
        headerView = getLayoutInflater().inflate(R.layout.item_mainlv_top,null);
        todayLv.addHeaderView(headerView);
        //2.查找头布局当中的控件
        topOutTv = headerView.findViewById(R.id.item_mainlv_top_tv_out);
        topInTv = headerView.findViewById(R.id.item_mainlv_top_tv_in);
        topbudgetTv = headerView.findViewById(R.id.item_mainlv_top_tv_budget);
        topConTv = headerView.findViewById(R.id.item_mainlv_top_tv);
        topShowIv = headerView.findViewById(R.id.item_mainlv_top_iv_hide);

        headerView.setOnClickListener(this);
        topShowIv.setOnClickListener(this);
        topbudgetTv.setOnClickListener(this);

    }
    /* 在头布局当中显示数据的方法*/
    private void setTopTvShow() {
        float incomeOneDay = DBManager.getSumAccountOneDay(year, month, day, 1);
        float outcomeOneDay = DBManager.getSumAccountOneDay(year, month, day, 0);
        String infoOneDay = "今日支出 ￥"+outcomeOneDay+"  收入 ￥"+incomeOneDay;
        topConTv.setText(infoOneDay);
        //获取本月支出和收入
        float incomeOneMonth = DBManager.getSumAccountOneMonth(year, month, 1);
        float outcomeOneMonth = DBManager.getSumAccountOneMonth(year, month, 0);
        topOutTv.setText("￥"+outcomeOneMonth);
        topInTv.setText("￥"+incomeOneMonth);

        //设置显示预算剩余
        float bmoney = preferences.getFloat("bmoney", 0);
        if(bmoney==0){
            topbudgetTv.setText("￥ 0");
        }else{
            float syMoney = FloatUtil.sub(bmoney,outcomeOneMonth);
            topbudgetTv.setText("￥"+syMoney);
        }
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();   // 得到被点击的view的id
        switch (id) {
            case R.id.main_btn_edit:    //点击记一笔按钮，跳转到编辑页面
                Intent intent = new Intent(this, RecordActivity.class);
                startActivity(intent);
                break;
            case R.id.main_btn_more:
                MoreDialog moreDialog = new MoreDialog(this);
                moreDialog.show();
                moreDialog.setDialogSize();
                break;
            case R.id.main_iv_search:
                Intent it = new Intent(this, SearchActivity.class);
                startActivity(it);

                break;
            case R.id.item_mainlv_top_iv_hide:
                // 切换明文和密文的方法
                toggleShow();
                break;
            case R.id.item_mainlv_top_tv_budget:
                showBudgetDialog();
                break;
        }
        if (v==headerView) {
            Intent intent = new Intent(this, MonthChartActivity.class);
            startActivity(intent);
        }
    }
    /* 显示预算设置对话框*/
    private void showBudgetDialog() {
        BudgetDialog dialog = new BudgetDialog(this);
        dialog.show();
        dialog.setDialogSize();
        dialog.setOnEnsureListener(new BudgetDialog.OnEnsureListener() {
            @Override
            public void onEnsure(float money) {
                 // 将预算的金额使用共享参数进行临时存储
                SharedPreferences.Editor editor = preferences.edit();   //得到写入数据的editor对象
                editor.putFloat("bmoney",money);
                editor.commit();
                float outcomeOneMonth = DBManager.getSumAccountOneMonth(year, month, 0);
                money=FloatUtil.sub(money,outcomeOneMonth);  // 预算剩余钱数=预算金额-本月支出
                topbudgetTv.setText("￥"+money);
            }
        });
    }

    boolean isShow = true;
    // 点击眼睛时，执行的方法，如果是明文，就加密，如果是密文，就显示出来
    private void toggleShow() {
        if (isShow) {
            PasswordTransformationMethod passwordmethod = PasswordTransformationMethod.getInstance();
            topInTv.setTransformationMethod(passwordmethod);//隐藏
            topOutTv.setTransformationMethod(passwordmethod);//隐藏
            topbudgetTv.setTransformationMethod(passwordmethod);
            topShowIv.setImageResource(R.mipmap.ih_hide);
            isShow = false;
        }else{
            HideReturnsTransformationMethod hidemethod = HideReturnsTransformationMethod.getInstance();
            topInTv.setTransformationMethod(hidemethod);//显示
            topOutTv.setTransformationMethod(hidemethod);//显示
            topbudgetTv.setTransformationMethod(hidemethod);
            topShowIv.setImageResource(R.mipmap.ih_show);
            isShow = true;
        }
    }
}
